#coding=utf-8

from django.middleware.csrf import get_token
from utils import logs
from auth.models import AuthedApp, get_authedapp
from core import codes
from utils.http import JResponse


from django.db import connection
from utils import eggs


class PrintSqlMiddleware(object):

    def process_response(self, request, serialize_response):
        logs.info('Agent: %s' % request.META.get('HTTP_USER_AGENT'))
        for sql in connection.queries:
            logs.info('[DEBUG-SQL]%s;   time: %s' % (sql['sql'], sql['time']))
        return serialize_response


class GetTokenMiddleware(object):

    def process_response(self, request, response):
        if request.method in ("POST", "PUT", "DELETE"):
            get_token(request)
        return response
    
class AuthedAppMiddleware(object):
    '''验证授权的客户端请求, 不允许非授权的app请求服务端api'''
    
    def process_view(self, req, view, view_args, view_kwargs):
        app_key = req.REQUEST.get('app_key', '')
        
        try:
            client = get_authedapp(app_key) #TODO: do this using cache later
            if client and _check_sig(req, client.secret_key):
                return None
            return JResponse(codes.get('unauthed_client'))
        except AuthedApp.DoesNotExist:
            return JResponse(codes.get('unauthed_client'))
                
                
def _check_sig(req, secret_key):
    """
    path = /v1/auth/login
    sig = md5(path+SALT)
    """
    passed_sig = req.REQUEST.get('sig')
    if not passed_sig:
        return False
    path = req.get_full_path()
    path = path.replace('&sig=%s' % passed_sig, '').replace('sig=%s&' % passed_sig, '').replace('sig=%s' % passed_sig, '')
    return True if passed_sig == eggs.make_sig(path, secret_key) else False


class PrintRequestParamsMiddleware(object):
    '''Add this middleware for printing request params when api requesting'''

    def process_request(self, request):
        logs.debug('')
        logs.debug('------------------ Request Params pre-view ------------------ begin')
        logs.debug('%s %s' % (request.method, request.path))
        logs.debug('Params: %s' % request.REQUEST)
        logs.debug('Http User Agent: %s' % request.META.get('HTTP_USER_AGENT', None))
        
        # only for testing, remove when online
        #client = get_authedapp(app_key=request.REQUEST.get('app_key', ''))
        #if not client:
        #    return
        #logs.info('sig: %s' % eggs.make_sig(request.get_full_path(), client.secret_key))
        
        #logs.info('FILES: %s' % request.FILES)
        logs.debug('------------------ Request Params pre-view  ----------------- end')
        logs.debug('')
